<?php
    
    function dz_link($row) {
        $dz_name = utf8_encode($row['dz_name']);

        if ($row['spotify_id']) {
            return '<a href='.make_spotify_http_link($row['spotify_id']).'>'.$dz_name.'</a>';
        } else {
            return $dz_name;
        }
    }
    
    function make_spotify_http_link($spotify_id) {
        return "http://open.spotify.com/track/$spotify_id";
    }

    function trim_halfword($str) {
        if (strlen($str) == 28) {
            $last_space = strrpos($str, ' ');
            $str = substr($str, 0, $last_space);
        }

        return $str;
    }

    function get_spotify_id($artist, $song) {
        # Drop "featuring:" in artist name.
        
        $artist = str_replace('&#039;', "'", $artist);
        $song = str_replace('&#039;', "'", $song);
        $artist = html_entity_decode($artist);
        $song = html_entity_decode($song);
        
        $feat_pos = strpos($artist, " Feat. ");
        if ($feat_pos > 3) {
            $artist = substr($artist, 0, $feat_pos);
        }

        $artist = utf8_encode(trim(trim_halfword($artist)));
        $song = utf8_encode(trim(trim_halfword($song)));
        $artist_normalized = str_replace("&", " ", $artist);
        $song_normalized = str_replace("&", " ", $song);

        $query = urlencode('artist:'.$artist_normalized.' track:'.$song_normalized);
        $query = 'http://ws.spotify.com/search/1/track?q='.$query;
	    $xml = file_get_contents($query,'r');			
      
        require_once('simplexml/IsterXmlSimpleXMLImpl.php');
        $impl = new IsterXmlSimpleXMLImpl;
        $doc  = $impl->load_string($xml);

        // access children
        $bestscore = 100;
        $bestpick = "";
        foreach( $doc->tracks->children() as $track ) {
            if ($track->getName() != "track") {
                continue;
            }
            
            if (!$track->name || !$track->artist) {
                continue;
            }
            
            foreach ($track->artist as $track_artist) {
                if (!$track_artist->name) {
                    continue;
                }
                $score = levenshtein($track->name->CDATA(), $song) +
                         levenshtein($track_artist->name->CDATA(), $artist);
                         
                if ($score < $bestscore) {
                    $attrs = $track->attributes();
                    $bestpick = $attrs['href'];
                    $bestscore = $score;
                }
                
                #print $track_artist->name->CDATA()." / ".$track->name->CDATA().": $score<br />"; 
            }
        }
        
        if ($bestscore > 10) {
            return null;
        }

        return str_replace("spotify:track:", "", $bestpick);  
    }
    
?>
